package com.web.startup;

import com.core.shared.Log;
import com.core.shared.CommonUtils;
import com.core.shared.file.FileHandle;
import org.apache.log4j.PropertyConfigurator;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: lxf
 * Date: 2017/4/21
 * Time: 14:05
 * To change this template use Editor | File and Code Templates.
 */
public class Server implements ServletContextListener {


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Log.getLogger(Server.class).info("Server is beginning !");
        //logInit(sce.getServletContext().getRealPath("/"));

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Log.getLogger(Server.class).info("Server is safety closed !");
    }

    private void logInit(String contextPath) {
        FileInputStream fis = null;
        try {
            Properties properties = new Properties();
            fis = new FileInputStream(contextPath + "/WEB-INF/classes/config.properties");
            properties.load(fis);
            fis.close();
            String logPath = properties.getProperty("logs.path");
            if (CommonUtils.isEmpty(logPath)) {
                throw new RuntimeException("The Logs Path is not specified !");
            }
            if (!FileHandle.createMenu(logPath)) {
                throw new RuntimeException("Has no Privilege to write the logs path");
            }
            System.setProperty("systemLogDir", logPath);
            //打印相关日志到文件中
            PropertyConfigurator.configure(contextPath + "/WEB-INF/classes/log4j.properties");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
